﻿using AutoMapper;
using MediatR;
using SCM.API.Write.Application.Command.Sale;
using SCM.API.Write.Application.Command.SaleRefund;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Implement;
using SCM.Infrastructure.Interface;
using System.Security.Claims;

namespace SCM.API.Write.Application.Handler.SaleRefund
{
    public class AddSaleRefundHandler : IRequestHandler<AddSaleRefundCommand, APIResult<int>>
    {
        IMapper mapper;
        DatabaseContext db;
        ILogger<AddSaleRefundHandler> logger;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public AddSaleRefundHandler(IMapper mapper, DatabaseContext db, ILogger<AddSaleRefundHandler> logger, IHttpContextAccessor httpContextAccessor)
        {
            this.mapper = mapper;
            this.db = db;
            this.logger = logger;
            _httpContextAccessor = httpContextAccessor;
        }

        public async Task<APIResult<int>> Handle(AddSaleRefundCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model = mapper.Map<SaleRefundModel>(request);


                ////获取创建人id
                //var userIdClaim = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
                //if (!int.TryParse(userIdClaim, out int userId))
                //{
                //    result.Code = APIEnum.Fail;
                //    result.Msg = "无法获取有效的用户ID";
                //    return await Task.FromResult(result);
                //}
                //model.MadeName = userId;
                //model.MadeTime = DateTime.Now;
                //model.UpdateName = null;
                //model.CreateTime = null;

                var purchas = db.SqlSugar.Queryable<SaleRefundModel>().Where(c => c.SaleRefundNum == request.SaleRefundNum && !c.IsDel).Count();
                if (purchas > 0)
                {
                    logger.LogError("退货单号唯一");
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货单号唯一";
                    return await Task.FromResult(result);
                }

                if (string.IsNullOrEmpty(model.SaleRefundNum))
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货单号不能为空";
                    return await Task.FromResult(result);
                }

                if (model.RefundNum <= 0)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货数量必须大于 0";
                    return await Task.FromResult(result);
                }
                var saleExists = await db.SqlSugar.Queryable<SaleManagementModel>().Where(p => p.SaleId == request.SaleId).FirstAsync();
                if (saleExists == null)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = $"销售单{request.SaleId}不存在，无法退货";
                    result.Data = 0;
                    return await Task.FromResult(result);
                }
                if (saleExists.State != 1)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = $"销售单状态为{saleExists.State}，不允许退货";
                    return await Task.FromResult(result);
                }

                if (model.RefundNum > saleExists.RefundNum)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = $"退货数量 {model.RefundNum} 超过销售单已发货数量 {saleExists.RefundNum}";
                    return await Task.FromResult(result);
                }


                if (saleExists.CustomerId != model.CustomerId)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "销售单与退货单的客户不匹配，无法退货";
                    return await Task.FromResult(result);
                }


                if (request.State < 1 || request.State > 3)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "状态值只能为1~3";
                    result.Data = 0;
                    return await Task.FromResult(result);
                }
                int r = db.SqlSugar.Insertable(model).ExecuteCommand();
                if (r > 0)
                {
                    result.Msg = "添加销售退货单信息成功";
                    result.Data = r;
                    result.Code = APIEnum.Success;
                }
                else
                {
                    result.Msg = "添加销售退货单信息失败";
                    result.Data = r;
                    result.Code = APIEnum.Fail;
                }
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "处理销售退货添加时发生异常");
                throw;
            }
        }
    }
}
